import * as React from 'react';
import TodoInput from './components/TodoList/TodoInput'
import { IListItemMeta } from './components/TodoList/TodoItem'
import TodoList from './components/TodoList/TodoList'
import StoreKey from './enums/store_key'

interface IState {
  list: IListItemMeta[];
}

const initialState:IState = {
  list: []
}

const storedState = window.localStorage.getItem(StoreKey.TodoList)

if (storedState) {
  initialState.list = JSON.parse(storedState);
}

class App extends React.Component<{}, IState> {
  public state = initialState
  public render() {
    return (
      <div className="ts-app">
        <h4 className="app__title">Todo App</h4>
        <TodoInput onAdd={this.addTodo}/>
        <TodoList
          list={this.state.list}
          onDelete={this.onDelete}
          onToggleDone={this.onToggleDone}
          onChangeInfo={this.onChangeInfo}
        />
      </div>
    )
  }
  public componentDidUpdate({}, state: IState) {
    // 每一步操作将state存入store中
    this.saveListToStore();
  }
  public addTodo = (val: string) => {
    this.setState({
      list: [
        ...this.state.list,
        {
          desc: val,
          id: new Date().getTime(),
          isDone: false
        }
      ]
    })
  }
  public onDelete = (id: number) => {
    const { list } = this.state;
    const idx = this.findIndex(list, item => item.id === id);
    if (idx >= 0) {
      this.setState({
        list: [
          ...list.slice(0, idx),
          ...list.slice(idx + 1)
        ]
      })
    }
  }
  public onToggleDone = (id: number) => {
    const { list } = this.state;
    const idx = this.findIndex(list, item => item.id === id);
    if (idx >= 0) {
      list[idx].isDone = !list[idx].isDone
    }
    this.setState({list: [...list]})
  }
  public onChangeInfo = (val: string, id: number) => {
    const { list } = this.state;
    const idx = this.findIndex(list, item => item.id === id);
    if (val) {
      list[idx].desc = val;
      this.setState({list: [...list]})
    } else {
      this.onDelete(id);
    }
  }
  private findIndex = (list: any[], fn: (arg: any) => boolean) => {
    let idx = -1;
    for (let i = 0; i < list.length; i++) {
      if (fn(list[i])) {
        idx = i;
        break;
      }
    }
    return idx;
  }
  private saveListToStore() {
    const { list } = this.state;
    window.localStorage.setItem(StoreKey.TodoList, JSON.stringify(list));
  }
}

export default App;
